<template>
    <div id="lanSetting">
        <div class="page-content-text">
            <HeaderLayout :title="$t('netWork.lanSettings.lanSettingsTitle')" />
            <template>
                <div v-if="!this.editFlag" class="page-content-normal">
                    <div class="flex-row" style="margin-bottom: 30px">
                        <div>
                            <div class="contentTitle_edit" id="lanAddressTitle">{{ $t('netWork.lanSettings.ipaddressTitle') }}</div>
                            <div class="contentValue_16B" id="address">{{ inputForm.ipAddress }}</div>
                        </div>
                        <div>
                            <el-link id="editButton" class="fr-edit" type="primary" :underline="false" @click="edit" v-if="!isHideEdit">{{ $t('common.editButton') }}</el-link>
                            <div v-else id="editButton" class="fr-edit-disabled">{{ $t('common.editButton') }}</div>
                        </div>
                    </div>

                    <div class="row_100">
                        <div class="contentTitle_edit" id="subnetMaskTitle">{{ $t('netWork.lanSettings.subnetMaskTitle') }}</div>
                        <div class="contentValue_16B" id="mask">{{ inputForm.mask }}</div>
                    </div>

                    <div v-if="!isShowDhcpSwitch" class="row_100">
                        <div class="contentTitle_edit" id="DHCPServerTitle">{{ $t('netWork.lanSettings.DhcpServerTitle') }}</div>
                        <div class="contentValue_16B" id="dhcpServer">{{ inputForm.dhcpEnable == 1 ? `${$t('common.enableLable')}` : `${$t('common.disableLable')}` }}</div>
                    </div>

                    <div class="row_100">
                        <div class="contentTitle_edit">{{ $t('netWork.lanSettings.DhcpRangeTitle') }}</div>
                        <div id="dhcpRange" class="contentValue_16B">{{ inputForm.dhcpRangeStart }}~{{ inputForm.dhcpRangeEnd }}</div>
                    </div>

                    <div class="row_100">
                        <div class="contentTitle_edit" id="dHCPLeaseTimeTitle">{{ $t('netWork.lanSettings.DHCPLeaseTitle') }}</div>
                        <div class="contentValue_16B" id="dhcpLease">{{ inputForm.dhcpLease }} {{ $t('netWork.lanSettings.secondsTitle') }}</div>
                    </div>
                </div>

                <div v-else class="page-content-edit">
                    <el-form :model="inputForm" ref="inputForm" :rules="inputFormRules" :inline="true">
                        <div class="row_mobile">
                            <div class="contentTitle_edit" id="lanAddressTitle"><star />{{ $t('netWork.lanSettings.ipaddressTitle') }}</div>
                            <div id="ipAddressInputBox">
                                <el-form-item prop="ipAddress0">
                                    <el-input
                                        id="ip1_edit"
                                        ref="inputRefs0"
                                        @input="handleInput(0)"
                                        @focus="handleFocus(0)"
                                        maxlength="3"
                                        minlength="1"
                                        class="ipAddressInput"
                                        v-model="inputForm.ipAddress0"
                                        onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                    ></el-input>
                                    <p class="dot">.</p>
                                </el-form-item>
                                <el-form-item prop="ipAddress1">
                                    <el-input
                                        id="ip2_edit"
                                        ref="inputRefs1"
                                        @input="handleInput(1)"
                                        @focus="handleFocus(1)"
                                        maxlength="3"
                                        minlength="1"
                                        class="ipAddressInput"
                                        v-model="inputForm.ipAddress1"
                                        onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                    ></el-input>
                                    <p class="dot">.</p>
                                </el-form-item>
                                <el-form-item prop="ipAddress2">
                                    <el-input
                                        id="ip3_edit"
                                        ref="inputRefs2"
                                        @input="handleInput(2)"
                                        @focus="handleFocus(2)"
                                        maxlength="3"
                                        minlength="1"
                                        class="ipAddressInput"
                                        v-model="inputForm.ipAddress2"
                                        onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                    ></el-input>
                                    <p class="dot">.</p>
                                </el-form-item>
                                <el-form-item prop="ipAddress3">
                                    <el-input
                                        id="ip4_edit"
                                        ref="inputRefs3"
                                        @input="handleInput(3)"
                                        @focus="handleFocus(3)"
                                        maxlength="3"
                                        minlength="1"
                                        class="ipAddressInput"
                                        v-model="inputForm.ipAddress3"
                                        onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                        @blur="onBlurIp3"
                                    ></el-input>
                                </el-form-item>
                            </div>
                        </div>
                        <div>
                            <div class="contentTitle_edit"><star />{{ $t('netWork.lanSettings.subnetMaskTitle') }}</div>
                            <el-form-item prop="mask">
                                <el-select v-model="inputForm.mask" id="maskSelect" @change="onChangeMask">
                                    <div id="maskOptions">
                                        <el-option v-for="item in maskArr" :key="item.value" :label="item" :value="item"> </el-option>
                                    </div>
                                </el-select>
                            </el-form-item>
                        </div>

                        <div v-if="!isShowDhcpSwitch" class="row_100">
                            <div class="contentTitle_edit" id="DHCPServerTitle"><star />{{ $t('netWork.lanSettings.DhcpServerTitle') }}</div>
                            <el-form-item prop="dhcpEnable">
                                <el-radio id="dhcpEnable" v-model="inputForm.dhcpEnable" label="1">{{ $t('common.enableLable') }}</el-radio>
                                <el-radio id="dhcpDisable" v-model="inputForm.dhcpEnable" label="0">{{ $t('common.disableLable') }}</el-radio>
                            </el-form-item>
                        </div>

                        <div>
                            <div class="contentTitle_edit"><star />{{ $t('netWork.lanSettings.DhcpRangeTitle') }}</div>
                            <p class="ipPrefix" style="line-height: 48px">
                                {{ `${this.inputForm.ipAddress0}.${this.inputForm.ipAddress1}.${this.inputForm.ipAddress2}.` }}
                            </p>
                            <el-form-item prop="dhcpRangeStart3">
                                <el-input
                                    id="dhcpRangeStart_edit"
                                    ref="inputRefs4"
                                    @change="validateDhcpRange('dhcpRangeEnd3')"
                                    @input="handleInput(4)"
                                    @focus="handleFocus(4)"
                                    maxlength="3"
                                    minlength="1"
                                    class="ipAddressInput"
                                    v-model="inputForm.dhcpRangeStart3"
                                    :disabled="!getDhcpStatus"
                                    onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                ></el-input>
                            </el-form-item>

                            <p class="ipPrefix" style="line-height: 48px">{{ `~${this.inputForm.ipAddress0}.${this.inputForm.ipAddress1}.${this.inputForm.ipAddress2}.` }}</p>
                            <el-form-item prop="dhcpRangeEnd3">
                                <el-input
                                    id="dhcpRangeEnd_edit"
                                    ref="inputRefs5"
                                    @change="validateDhcpRange('dhcpRangeStart3')"
                                    @input="handleInput(5)"
                                    @focus="handleFocus(5)"
                                    maxlength="3"
                                    minlength="1"
                                    class="ipAddressInput"
                                    v-model="inputForm.dhcpRangeEnd3"
                                    :disabled="!getDhcpStatus"
                                    onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"
                                ></el-input>
                            </el-form-item>
                        </div>

                        <div class="row_100">
                            <div class="contentTitle_edit" id="dHCPLeaseTimeTitle"><star />{{ $t('netWork.lanSettings.DHCPLeaseTitle') }}</div>
                            <el-form-item prop="dhcpLease">
                                <el-input id="dhcpLease_edit" style="width: 150px" :disabled="!getDhcpStatus" v-model="inputForm.dhcpLease" maxlength="7" minlength="3" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46"></el-input>
                            </el-form-item>
                            <p class="secondsuffix">{{ $t('netWork.lanSettings.secondsTitle') }}</p>
                        </div>
                        <div style="height: 30px; line-height: 30px"></div>
                        <el-form-item>
                            <el-button id="saveButton" type="primary" round @click="sumbit">{{ $t('common.saveButton') }}</el-button>
                            <el-button id="cancelButton" type="info" @click="cancelEdit">{{ $t('common.cancelButton') }}</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </template>
        </div>

        <confirm-dialog ref="confirmDialog" :title="$t('netWork.lanSettings.confirmchanges')" @confirm="setLaninfo">
            <div>{{ $t('netWork.lanSettings.confirmTips') }}</div>
        </confirm-dialog>

        <confirm-dialog ref="countdownRef" :title="$t('netWork.lanSettings.waitingforLANSetting')" :count="35" @countdownEnd="countdownEnd">
            <span>{{ $t('netWork.lanSettings.wlsMsg1') }}</span>
        </confirm-dialog>
    </div>
</template>

<script>
import { isEqualCIDR, IPNetworkSegment } from '@/utils/network.js';
import { errorCode, serverError } from '@/constant/dict';
import {getLanConfigInfo,updateLanInfo} from '@/api/mobile';

export default {
    components: {
    },
    data() {
        // ip0 校验
        const validatorIp0 = (rule, value, callback) => {
            if (value) {
                // ip0 == 10||172||192 true
                if (value == 10 || value == 172 || value == 192) {
                    callback();
                } else {
                    // else false
                    callback(new Error('10/172/192'));
                }
            } else {
                callback(new Error('10/172/192'));
            }
        };

        // ip1 校验
        const validatorIp1 = (rule, value, callback) => {
            if (value) {
                const ip0 = this.inputForm.ipAddress0; // 获取 ip0
                const _value = +value;
                if (ip0 == 10) {
                    // ip0 = 10
                    if (_value >= 0 && _value < 256) {
                        // ip1 在 0-255 范围内
                        callback();
                    } else {
                        callback(new Error('0-255'));
                    }
                } else if (ip0 == 172) {
                    // ip0 = 172
                    if (_value > 15 && _value < 32) {
                        // ip1 在 16-31 范围内
                        callback();
                    } else {
                        callback(new Error('16-31'));
                    }
                } else if (ip0 == 192) {
                    // ip0=192
                    if (_value == 168) {
                        // ip1 只能是 168
                        callback();
                    } else {
                        callback(new Error('168!'));
                    }
                } else {
                    callback(new Error('0-255'));
                }
            } else {
                callback(new Error('0-255'));
            }
        };

        // ip2 校验
        const validatorIp2 = (rule, value, callback) => {
            if (!value) {
                callback(new Error('1-254'));
            } else {
                callback();
            }
        };

        // ip3校验
        const validatorIp3 = (rule, value, callback) => {
            if (value) {
                const start = this.inputForm.dhcpRangeStart3; // dhcp start
                const end = this.inputForm.dhcpRangeEnd3; // dhcp end
                const validRes = this.validBroadAndNetwork();
                if (validRes === errorCode.EQUAL_NETWORK_ADDRESS) {
                    callback(new Error(this.$t('netWork.lanSettings.lanIpNotEqualNetworkAddress')));
                }
                if (validRes === errorCode.EQUAL_BROAD_ADDRESS) {
                    callback(new Error(this.$t('netWork.lanSettings.lanIpNotEqualBroadCastAddress')));
                }
                // ip3 = dhcp start 或者 ip3 = dhcp end
                if (value === start || value === end) {
                    callback(new Error(this.$t('netWork.lanSettings.equalsRouter')));
                } else {
                    callback();
                }
            } else {
                callback(new Error('1-254'));
            }
        };

        // dhcp lease 校验
        const validatorDhcpLease = (rule, value, callback) => {
            if (+value < 120 || +value > 1800000) {
                callback(new Error('120-1800000'));
            } else {
                callback();
            }
        };

        // dhcp start 校验
        const validatorDhcpRangeStart = (rule, value, callback) => {
            const ip3 = +this.inputForm.ipAddress3; // ip
            const end = +this.inputForm.dhcpRangeEnd3; // 结束值
            const min = +this.minDhcpRange; // 最小值
            const max = +this.maxDhcpRange; // 最大值
            const _value = +value;
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
                return;
            }
            if (_value == ip3) {
                callback(new Error(this.$t('netWork.lanSettings.equalsRouter')));
                return;
            }

            if (_value < min || _value > max) {
                if (_value < min || _value > max) {
                    const rangeError = getRangeError(min, max, ip3);
                    return callback(new Error(rangeError));
                }
            }

            if (end >= min && end <= max && _value > end && end > 0) {
                callback(new Error(`${this.$t('errorTips.lessThanOrEqual')} ${end}`));
                return;
            }

            callback();
        };

        // dhcp end 校验
        const validatorDhcpRangeEnd = (rule, value, callback) => {
            const ip3 = +this.inputForm.ipAddress3;
            const start = +this.inputForm.dhcpRangeStart3;
            const min = +this.minDhcpRange;
            const max = +this.maxDhcpRange;
            const _value = +value;
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
                return;
            }
            if (_value == ip3) {
                callback(new Error(this.$t('netWork.lanSettings.equalsRouter')));
                return;
            }
            if (_value < min || _value > max) {
                const rangeError = getRangeError(min, max, ip3);
                return callback(new Error(rangeError));
            }
            if (_value >= min && _value <= max && start >= min && start <= max) {
                if (_value < start) {
                    return callback(new Error(`${this.$t('errorTips.greaterThanOrEqual')} ${start}`));
                }
            }
            callback();
        };

        const getRangeError = (min, max, ip3) => {
            if (max - min === 1) {
                if ([min, max].includes(ip3)) {
                    const range = [min, max].find((item) => item != ip3);
                    return range;
                }
                return `${min}~${max}`;
            }
            if (ip3 > min && ip3 < max) {
                return `${min}~${ip3 - 1},${ip3 + 1}~${max}`;
            } else if (ip3 === min) {
                return `${min + 1}~${max}`;
            } else if (ip3 === max) {
                return `${min}~${max - 1}`;
            } else {
                return `${min}~${max}`;
            }
        };

        return {
            ipptStatus: false,
            isEqualCIDR: isEqualCIDR,
            mInputForm: {},
            inputForm: {
                ipAddress: '',
                ipAddress0: '',
                ipAddress1: '',
                ipAddress2: '',
                ipAddress3: '',
                mask: '',
                dhcpEnable: '',
                dhcpRangeStart: '',
                dhcpRangeStart3: '',
                dhcpRangeEnd: '',
                dhcpRangeEnd3: '',
                dhcpLease: ''
            },
            inputFormRules: {
                ipAddress0: [{ validator: validatorIp0, trigger: 'blur' }],
                ipAddress1: [{ validator: validatorIp1, trigger: 'blur' }],
                ipAddress2: [
                    { pattern: /^(25[0-5]|2[0-4]\d|[01]?\d{1,2})$/, message: '0-255', trigger: 'blur' },
                    { validator: validatorIp2, trigger: 'blur' }
                ],
                ipAddress3: [
                    { pattern: /^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$/, message: '1-254', trigger: 'blur' },
                    { validator: validatorIp3, trigger: 'blur' }
                ],
                dhcpLease: [
                    { pattern: /^\+?[1-9]\d*$/, message: '120-1800000', trigger: 'blur' },
                    { validator: validatorDhcpLease, trigger: 'blur' }
                ],
                dhcpRangeStart3: [{ validator: validatorDhcpRangeStart, trigger: ['blur', 'change'] }],
                dhcpRangeEnd3: [{ validator: validatorDhcpRangeEnd, trigger: ['blur', 'change'] }]
            },
            easyMeshStatus: true,
            sumbitVisbile: false,
            laninfo: {},
            editFlag: false,
            dhcpRange: false,
            maskArr: ['255.255.255.0', '255.255.255.128', '255.255.255.192', '255.255.255.224', '255.255.255.240', '255.255.255.248', '255.255.255.252'],
            minDhcpRange: '', // 根据 ip和子网掩码 &出来的得到的 dhcpRange 最后一位的最小值
            maxDhcpRange: '', // 根据 ip和子网掩码 &出来的得到的 dhcpRange 最后一位的最大值
            netNumberCheckFlag: false,
            rangeCheckFlag: false,
            dhcpConflictFlag: false,
            leaseFlag: false,
            errorStatus: '',
        };
    },
    computed: {
        getDhcpStatus() {
            return this.inputForm.dhcpEnable === '1';
        },
        isChangeLanIp() {
            return this.mInputForm.ipAddress !== this.inputForm.ipAddress;
        },
        isHideEdit() {
            if (this.ipptStatus) return true;
            if (!this.easyMeshStatus) return true;
            return false;
        },
        isShowDhcpSwitch() {
            return false;
        }
    },
    created() {
        this.getLanInfo();
    },
    methods: {
        openCountdownDialog() {
            this.$refs.countdownRef.show();
            this.$refs.countdownRef.changeDialogStyle();
        },
        onBlurIp3() {
            this.getDHCPRange();
        },
        onChangeMask() {
            this.getDHCPRange();
        },
        validBroadAndNetwork: function () {
            const { ipAddress0, ipAddress1, ipAddress2, ipAddress3, mask } = this.inputForm;
            const ipAddress = `${ipAddress0}.${ipAddress1}.${ipAddress2}.${ipAddress3}`;
            const res = this.isEqualCIDR(ipAddress, mask);
            return res;
        },
        async getLanInfo() {
            //获取lan信息
            try {
                console.log('[getLanInfo] 尝试获取LAN配置信息...');
                const res = await getLanConfigInfo();
                 
                console.log('[getLanInfo] 成功获取LAN配置信息: ', res);
                this.laninfo = res;
            } catch (error) {
                console.error('[getLanInfo] 获取LAN配置信息失败:', error);
            }

         
            this.render();
        },

        edit() {
            this.editFlag = true;
        },
 
        render() {
            const { ip_address = "", net_mask = "", dhcp_enable = false, dhcp_range_start= "", dhcp_range_end= "", dhcp_lease= "" } = this.laninfo;
            console.log("lan信息1:",this.laninfo);
            console.log("ip_address:",ip_address);

            this.inputForm = {
                ipAddress: ip_address,
                mask: net_mask,
                dhcpEnable: dhcp_enable,
                dhcpRangeStart: dhcp_range_start,
                dhcpRangeEnd: dhcp_range_end,
                dhcpLease: dhcp_lease,
                ...dhcp_range_start.split('.').reduce((acc, val, i) => ({ ...acc, [`dhcpRangeStart${i}`]: val }), {}),
                ...dhcp_range_end.split('.').reduce((acc, val, i) => ({ ...acc, [`dhcpRangeEnd${i}`]: val }), {}),
                ...ip_address.split('.').reduce((acc, val, i) => ({ ...acc, [`ipAddress${i}`]: val }), {})
            };
            console.log("inputForm1:",this.inputForm);

            this.mInputForm = JSON.parse(JSON.stringify(this.inputForm));
            // 初始化时，获取 DHCP Range 最大最小值
            this.getDHCPRange(false);
        },

        cancelEdit() {
            this.editFlag = false;
            this.getLanInfo();
        },

        sumbit() {
            this.$refs.inputForm.validate(async (valid) => {
                if (valid) {
                    const { ipAddress0, ipAddress1, ipAddress2, ipAddress3 } = this.inputForm;

                    this.inputForm.ipAddress = `${ipAddress0}.${ipAddress1}.${ipAddress2}.${ipAddress3}`;
                    this.$refs.confirmDialog.show();
                }
            });
        },


      

        // 发起设置请求
        async setLaninfo() {
            this.$refs.confirmDialog.hide();
            const lanConfig = {
                // IP 配置
                ip_address: `${this.inputForm.ipAddress}`,
                net_mask: this.inputForm.mask,
                // DHCP 配置
                dhcp_enable: this.inputForm.dhcpEnable,
                dhcp_range_start:  `${this.inputForm.ipAddress0}.${this.inputForm.ipAddress1}.${this.inputForm.ipAddress2}.${this.inputForm.dhcpRangeStart3}`,
                dhcp_range_end:  `${this.inputForm.ipAddress0}.${this.inputForm.ipAddress1}.${this.inputForm.ipAddress2}.${this.inputForm.dhcpRangeStart3}`,
                dhcp_lease: this.inputForm.dhcpLease
            };
            console.log("------------:",lanConfig);
            const res = await updateLanInfo(lanConfig);
            console.log("res:",res);
            // IP 和静态路由目的 IP 相同
            if (res == '-20') {
                return this.$message.error(this.$t('netWork.lanSettings.ipAndStaticIpErr'));
            }

            // IP 和 wanIp 在同一网段
            if (res == '-26') {
                return this.$message.error(this.$t('netWork.staticRouteSettings.wanipTips'));
            }

            // IP 和 MobileIp 相同
            if (res == '-28') {
                return this.$message.error(this.$t('netWork.staticRouteSettings.ipMobileIpTips'));
            }

            // 不在同一个网段
            if (res === serverError.ERR_VALID) {
                return this.$message.error(this.$t('common.error'));
            }

            console.log(res);
            if (res == 'success') {
                this.openCountdownDialog();
            } else {
                this.$message.error(this.$t('common.error'));
            }
        },

        // 倒计时结束
        countdownEnd() {
            this.editFlag = false;
            if (this.isChangeLanIp) {
                window.location.replace(`http://${this.inputForm.ipAddress}`);
            } else {
                this.getDHCPRange();
                this.getLanInfo();
            }
        },

        // 计算 DHCPRange 最后一位 最小值和最大值，修改 ip最后一位和 子网掩码都需要调用这个函数，得到最大最小值之后去校验， 然后判断 ip 是否 在 这个网段内
        getDHCPRange(isAssignment = true) {
            const ip3 = +this.inputForm.ipAddress3;
            if (ip3 > 0 && ip3 < 255) {
                // 跟 mask options对应相加 = 254
                let IPsetNumber = [254, 126, 62, 30, 14, 6, 2];
                let x;
                for (let i = 0; i < this.maskArr.length; i++) {
                    if (this.inputForm.mask == this.maskArr[i]) {
                        x = i;
                    }
                }
                let overlap = Math.floor(ip3 / (IPsetNumber[x] + 2));
                this.minDhcpRange = overlap * (IPsetNumber[x] + 2) + 1;
                this.maxDhcpRange = overlap * (IPsetNumber[x] + 2) + IPsetNumber[x];
            }
        },

     
       

        handleInput(index) {
            this.$nextTick(() => {
                const input = this.$refs[`inputRefs${index}`];
                const value = input.value;
                const regex = /\d+/g;
                const keyArr = ['ipAddress0', 'ipAddress1', 'ipAddress2', 'ipAddress3', 'dhcpRangeStart3', 'dhcpRangeEnd3'];
                if (value.length === 3 || value.includes('.')) {
                    for (let key in this.inputForm) {
                        keyArr.forEach((refKey) => {
                            if (refKey === key && typeof this.inputForm[refKey] === 'string') {
                                this.inputForm[refKey] = this.inputForm[refKey].replace(/\D/g, '');
                            }
                        });
                    }

                    if (value.match(regex)) {
                        const nextInput = this.$refs[`inputRefs${index + 1}`];
                        if (nextInput) {
                            nextInput.select();
                            nextInput.focus();
                        }
                    }
                }
            });
        },

        handleFocus(index) {
            this.$nextTick(() => {
                const input = this.$refs[`inputRefs${index}`];
                input.select();
            });
        },

        validateDhcpRange(key) {
            this.$refs.inputForm.validateField(key);
        }
    }
};
</script>
<style lang="less" scoped>
@import '@/assets/css/theme_blue/component_common.less';
@import '@/assets/css/theme_blue/component_straight.less';
/deep/ .el-form-item__error {
    line-height: 1.3;
}
</style>
